using System.Reflection;
using System.Runtime.InteropServices;

namespace System.WindowsCe.Mvp.Utils
{
	public static class SingleInstance
	{
		private static IntPtr _handle;

		public static bool IsSingleInstance()
		{
			string appname = Assembly.GetExecutingAssembly().GetName().Name;
			_handle = CreateMutex(IntPtr.Zero, false, appname);

			var err = Marshal.GetLastWin32Error();
			if (err == ERROR_ALREADY_EXISTS)
			{
				return false;
			}
			return true;
		}

		public static void CloseHandle()
		{
			CloseHandle(_handle);
		}

		private const int ERROR_ALREADY_EXISTS = 183;

		[DllImport("coredll.dll", SetLastError = true)]
		private static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool InitialOwner, string MutexName);

		[DllImport("coredll.dll")]
		private static extern bool CloseHandle(IntPtr hMutex); 
	}
}